package org.kepler.chat.api.infra.handler;

import net.sf.json.JSONObject;
import org.bigdata.frame.exception.BizException;
import org.bigdata.frame.util.ReturnDatas;
import org.kepler.chat.api.infra.util.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class CustomRestExceptionResolver implements HandlerExceptionResolver {
	private static final Logger logger = LoggerFactory.getLogger(CustomRestExceptionResolver.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
		logger.error(e.getMessage(), e);
		int code = ErrorCode.SYS_ERROR.getCode();
		String msg = ErrorCode.SYS_ERROR.getMessage();
		if(e instanceof BizException){
			code = ((BizException) e).getErrorCode();
			msg = ((BizException) e).getErrorMessage();
		}
		printWrite(code, msg, httpServletResponse);
		return null;
	}

	/**
	 * 将错误信息添加到response中
	 *
	 * @param msg
	 * @param response
	 * @throws IOException
	 */
	public static void printWrite(int code, String msg, HttpServletResponse response) {
		try {
			ReturnDatas returnDatas = ReturnDatas.getErrorReturnDatas();
			returnDatas.setStatusCode(""+code);
			returnDatas.setMessage(msg);

			JSONObject j = JSONObject.fromObject(returnDatas);
			response.setContentType("application/json");
			response.setCharacterEncoding("utf-8");
			PrintWriter pw = response.getWriter();
			pw.write(j.toString());
			pw.flush();
			pw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
